package com.hanscan.util.signing;



import com.hanscan.persistence.entities.Event;
import java.util.Calendar;
import java.util.List;

public class DailySigning
{
   private List <Event> signings;
   private Calendar arrivalTime, endingTime, totalHoursWorked;
   private int day;


    public  DailySigning()
    {

    }


    /**
     * Constructor
     * @param signings Lista de fichajes del dia
     * @param dayOfMonth dia del mes
     */
    public DailySigning(List <Event> signings,int dayOfMonth)
    {
        //Cargar la lista de fichajes del dia
        this.signings = signings;
        int size = signings.size();

        //Cargar dia del mes
        this.day = dayOfMonth++;

        //Carga el primer fichaje del dia
        Calendar calendar = Calendar.getInstance();
        long millisecond = signings.get(0).getDateTime().getTime();
        calendar.setTimeInMillis(millisecond);
        this.arrivalTime = calendar;

        //cargar el ultimo fichaje del dia
        Calendar calendarLast = Calendar.getInstance();
        millisecond= signings.get(size -1).getDateTime().getTime();
        calendarLast.setTimeInMillis(millisecond);
        this.endingTime = calendarLast;

        //cargar las horas trabajadas
        this.totalHoursWorked = this.calculate(signings);
    }


    
   /**
   * Calcular las horas trabajadas en el dia
   * @param signings Lista de fichajes del dia
   * @return Caledar con las horas totales trabajadas en el dia
   */
   public Calendar calculate (List <Event> signings)
   {
        long totalMilliSecond = 0;
        long subTotalMilliSecond=0;
        Calendar timeWorked = null;
        Event previousSigning, nextSigning= null;
        int size = signings.size() - 1;
        long previousIncidence, nextIncidence=0;
        boolean countTime= false;

        System.out.println("signings size ... " +  signings.size());
        int numOcurrenciaMismaIncidencia=0;


        for (int i = 0; i< size; i++)
        {
            previousSigning = (Event) signings.get(i);
            nextSigning = (Event) signings.get(i + 1);
            previousIncidence =
                previousSigning.getEventType().getEventTypeValue();
            nextIncidence = nextSigning.getEventType().getEventTypeValue();

//            System.out.println("previousSigning.getIncidence().getIncidenceNumber()... " + previousSigning.getIncidence().getIncidenceNumber());
//            System.out.println("previousSigning.getDateTime().toString()... " + previousSigning.getDateTime().toString());
//            System.out.println("nextSigning.getIncidence().getIncidenceNumber();... " + nextSigning.getIncidence().getIncidenceNumber());
//            System.out.println("nextSigning.getDateTime().toString()... " + nextSigning.getDateTime().toString());

            countTime= false;

            if ((previousIncidence != nextIncidence))
            {
                numOcurrenciaMismaIncidencia=0;
                countTime= true;

                if(((previousIncidence == 2) && (nextIncidence == 1)))
                {
                    countTime= false;
                }
                if (nextIncidence == 0 )
                {
                    countTime= false;
                }
            }
            else
            {
                if ((numOcurrenciaMismaIncidencia%2)==0)
                {
                    countTime= false;
                }
                else
                {
                    countTime= true;
                }

                numOcurrenciaMismaIncidencia++;

            }

            if (countTime)
            {
                Calendar calendarPreviousSigning = Calendar.getInstance();
                calendarPreviousSigning.setTime(previousSigning.getDateTime());

                System.out.println("calendarPreviousSigning.getTime().toString() ..." + calendarPreviousSigning.getTime().toString());


                Calendar calendarNextSigning = Calendar.getInstance();
                calendarNextSigning.setTime(nextSigning.getDateTime());

                System.out.println("calendarNextSigning.getTime().toString() ..." +  calendarNextSigning.getTime().toString());




                
                subTotalMilliSecond =
                        diffTimeInMilliSecond(calendarPreviousSigning,
                        calendarNextSigning);
                totalMilliSecond = totalMilliSecond + subTotalMilliSecond;

                System.out.println("subTotalMilliSecond..." + subTotalMilliSecond);

                timeWorked = Calendar.getInstance();
                timeWorked.setTimeInMillis(totalMilliSecond);

                System.out.println("SUBtimeWorked. HOUR_OF_DAY ..." + timeWorked.get(Calendar.HOUR_OF_DAY));
                System.out.println("SUBtimeWorked. MINUTE ..." + timeWorked.get(Calendar.MINUTE));
                System.out.println("SUBtimeWorked. HOUR ..." + timeWorked.get(Calendar.HOUR));
                System.out.println("SUBtimeWorked. SECOND ..." + timeWorked.get(Calendar.SECOND));
                System.out.println("SUBtimeWorked. MILLISECOND ..." + timeWorked.get(Calendar.MILLISECOND));
        
                System.out.println("SUBtimeWorked..." + timeWorked.getTime().toString());

            }            
        }

        timeWorked = Calendar.getInstance();
        timeWorked.setTimeInMillis(totalMilliSecond);

        System.out.println("timeWorked..." + timeWorked.getTime().toString());

        return timeWorked;
    }

  /**
   * Calcular las horas trabajadas en el dia
   * @param signings Lista de fichajes del dia
   * @return Caledar con las horas totales trabajadas en el dia
   */
    public Calendar calculateAscari(List<Event> signings)
    {
        long total = 0, subTotal;
        Calendar hoursWork;
        Event firt, last;
        int i, size;
        size = signings.size() - 1;
        Calendar dayCalculate = Calendar.getInstance();
        Calendar toDay = Calendar.getInstance();
        dayCalculate.setTimeInMillis(signings.get(size - 1).getDateTime().getTime());

        if ((toDay.get(Calendar.MONTH) == dayCalculate.get(Calendar.MONTH)) &&
            (toDay.get(Calendar.YEAR) == dayCalculate.get(Calendar.YEAR)) &&
            (toDay.get(Calendar.DAY_OF_MONTH) == dayCalculate.get(Calendar.DAY_OF_MONTH)))
        {
            Calendar toDayHour = Calendar.getInstance();
            toDayHour.setTimeInMillis(signings.get(size).getDateTime().getTime());
            if ((toDayHour.get(Calendar.MINUTE) == 59) &&
                (toDayHour.get(Calendar.HOUR_OF_DAY) == 23))
            {
                size--;
            }
        }
        for (i = 0; i < size; i++)
        {
            firt = (Event) signings.get(i);
            last = (Event) signings.get(i + 1);

            Calendar frist = Calendar.getInstance();
            frist.setTime(firt.getDateTime());

            Calendar second = Calendar.getInstance();
            second.setTime(last.getDateTime());
            int val = i % 2;
            if (val == 0)
            {
                subTotal = diffTimeInMilliSecond(frist, second);
                total = total + subTotal;
            }
        }
        hoursWork = Calendar.getInstance();
        hoursWork.setTimeInMillis(total);
        return hoursWork;
    }

   /**
   * Calcula la diferencia de horas entre dos Calendar
   * @param a Calendar a comparar
   * @param b Calendar a comparar
   * @return long con la diferencia en milisegundos entre 2 dos fechas
   */
    public long diffTimeInMilliSecond(Calendar first, Calendar second)
    {
        int hours = second.get(Calendar.HOUR_OF_DAY) -
                    first.get(Calendar.HOUR_OF_DAY);
        int minutes = second.get(Calendar.MINUTE) - first.get(Calendar.MINUTE);
        minutes = minutes + (hours * 60);
        long diffTimeInMilliSecond = minutes * 60000;
        diffTimeInMilliSecond = second.getTimeInMillis() - first.getTimeInMillis();
        return diffTimeInMilliSecond;
    }


    //*****************************************************
    // getters y setters
    //******************************************************

     /**
     * get de la lista de fichajes diarios
     * @return List <Signing>
     */
    public List <Event> getSignings()
    {
        return signings;
    }

    /**
     * set de la lista de fichajes diarios
     * @param List <Signing>
     */
    public void setSignings(List <Event> signings)
    {
        this.signings = signings;
    }

    public Calendar getArrivalTime()
    {
        return arrivalTime;
    }

    public void setArrivalTime(Calendar arrivalTime)
    {
        this.arrivalTime = arrivalTime;
    }

    public Calendar getEndingTime()
    {
        return endingTime;
    }

    public void setEndingTime(Calendar endingTime)
    {
        this.endingTime = endingTime;
    }

    public int getDay()
    {
        return day;
    }

    public Calendar getTotalHoursWorked()
    {
        return totalHoursWorked;
    }

    public void setTotalHoursWorked(Calendar totalHoursWorked)
    {
        this.totalHoursWorked = totalHoursWorked;
    }

}
